var Fly = require("./wx.js") //wx.js为您下载的源码文件
var fly = new Fly; //创建fly实例
var tokenFly = new Fly();
import util from './index.js';
import config from '../config.js'
//添加finally方法
Promise.prototype.finally = function (callback) {
  let P = this.constructor;
  return this.then(
    value => P.resolve(callback()).then(() => value),
    reason => P.resolve(callback()).then(() => { throw reason })
  );
};

var token = wx.getStorageSync('token');
//设置超时

fly.config.timeout = 10000;
//设置请求基地址

tokenFly.config.baseURL = config.baseURL;
fly.config.baseURL = config.baseURL + config.miniAppName;
//给所有请求添加自定义header

fly.config.headers = tokenFly.config.headers = {
  "appkey": config.appkey,
  "content-type": "application/x-www-form-urlencoded",
  token,
}

//添加请求拦截器
fly.interceptors.request.use((request) => {
  if (!token) {
    fly.lock()
    return new Promise((resove, reject) => {
      //登陆
      wx.login({
        success: function (res) {
          let code = res.code;
          if (code) {
            //发起网络请求
            resove(code)
          } else {
            console.log('登录失败！')
          }
        }
      });
    }).then((code) => {

      return tokenFly.post("/xiaochengxu/Token/getToken", { code })

    }).then((d) => {
      request.headers["token"] = token = d.data.data.token;
      let uid = d.data.data.uid
      wx.setStorageSync("token", token);//保存token
      wx.setStorageSync("uid", uid);//保存uid
      return request;
    }).finally(() => {

      fly.unlock();//解锁后，会继续发起请求队列中的任务，详情见后面文档
      //关联
      let pid = wx.getStorageSync('pid')
      if (pid) {

        fly.post("api.member/save", { pid }).then(() => {
          //util.showModal({ content: "关联上下级成功" })
        })
      }

    })
  } else {
    request.headers["token"] = token;
  }
})

//添加响应拦截器，响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
  (response) => {
    //只将请求结果的data字段返回
    if (response.data.code == 200) {
      
      return response.data
    } else {
      wx.hideLoading();
      util.showModal({ content: response.data.msg })
      return false;
    }
  },
  (err) => {
    //发生网络错误后会走到这里
    //return Promise.resolve("ssss")
    util.hideAll()
    let status = err.status
    switch (status) {
      case 0: util.networkError({ msg: '网络错误' })
        break;
      case 1: util.networkError({ msg: '请求超时' }); break;
      case 2: util.showModal({ content: "文件保存失败" }); break;
      case 401: console.log("token过期，授权失败");
        
        fly.lock()
        return new Promise((resove, reject) => {
          //登陆
          wx.login({
            success: function (res) {
              let code = res.code;
              if (code) {
                //发起网络请求
                resove(code)
              } else {
                console.log('登录失败！')
              }
            },fail:function(){
              console.log('登录失败！')
            }
          });
        }).then((code) => {

          return tokenFly.post("/xiaochengxu/Token/getToken", { code })

        }).then((d) => {
          let uid = d.data.data.uid
          err.request.headers["token"] = token = d.data.data.token;
          wx.setStorageSync("token", token);//保存token
          wx.setStorageSync("uid", uid);//保存uid
        }).finally(() => {

          fly.unlock();//解锁后，会继续发起请求队列中的任务，详情见后面文档
          //关联
          let pid = wx.getStorageSync('pid')
          if (pid) {

            fly.post("api.member/save", { pid }).then(() => {
              //util.showModal({ content: "关联上下级成功" })
            })
          }
        }).then(() => {
          
          return fly.request(err.request); //只有最终返回request对象时，原来的请求才会继续
        });break;
      default: util.showModal({ content: err.response.data.msg });
    }

  }
)
const uploadFile = (url, { name = "file", filePath, formData={}}={})=>{
  
  url = config.baseURL+url;
  return new Promise((resove,reject)=>{
    wx.uploadFile({
      url,
      filePath,
      name,
      header: {
        appkey: config.appkey,
        token
      },
      formData,
      success: function (res) {
        if (res.statusCode==200){
          resove(res.data)
        }else{
          util.showModal({ content: "上传失败" })
        }
      },
      fail: function (res) {
        reject(false)
        util.showModal({ content: "上传失败" })
        wx.hideLoading();
      },
      complete: function (res) { },
    })
  }) 
}
//统一处理报错时，不再往下执行
const req = {
  post(url, param) {
    return new Promise((resove, reject) => {
      fly.post(url, param).then((d) => {
        if (d) resove(d)
      })
    })
  },
  get(url, param) {
    return new Promise((resove, reject) => {
      fly.get(url, param).then((d) => {
        if (d) resove(d)
      })
    })
  }
}
export { fly, req, uploadFile }